<template>
  <el-dialog v-loading="loading" :append-to-body="true" :close-on-click-modal="false" :visible.sync="visable" :title="isAdd ? '新增系统参数' : '编辑系统参数'" width="500px" @close="closeDlg">
    <el-form ref="xform" :model="form" :rules="rules" size="small" label-width="80px">
      <el-form-item label="编码" prop="key">
        <el-input v-model="form.key" maxlength="32" :disabled="!isAdd" />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" autocomplete="false" maxlength="60" :disabled="!isAdd" />
      </el-form-item>
      <el-form-item label="说明" prop="memo">
        <el-input v-model="form.memo" autocomplete="false" maxlength="200" :disabled="!isAdd" />
      </el-form-item>
      <el-form-item label="值" prop="value">
        <el-input v-model="form.value" autocomplete="false" maxlength="64" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'SysParamsForm',
  data() {
    return {
      isAdd: false,
      loading: false,
      visable: false,
      form: this.initForm(),
      rules: {
      }
    }
  },
  methods: {
    initForm() {
      return {
        key: '',
        name: '',
        memo: '',
        value: ''
      }
    },
    resetFields() {
      this.$refs['xform'].resetFields()
      this.form = this.initForm()
    },
    cancel() {
      this.closeDlg()
    },
    doSubmit() {
      this.$refs['xform'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.isAdd) {
            // this.doAdd()
          } else this.doEdit()
        }
      })
    },
    edit(id) {
      request({ url: '/sys/sysparams/' + id, method: 'get' }).then(data => {
        Object.keys(this.form).forEach(key => {
          if (typeof (data[key]) === 'undefined') {
            this.form[key] = ''
          } else {
            this.form[key] = data[key]
          }
        })
        this.isAdd = false
        this.visable = true
      }).catch(err => {
        this.$message.error(err.message)
      })
    },

    doEdit() {
      request({ url: '/sys/sysparams', method: 'put', data: this.form }).then(res => {
        this.closeDlg()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.getList()
      }).catch(err => {
        this.loading = false
        this.$message.error('修改错误！' + err.message)
      })
    },
    closeDlg() {
      this.visable = false
      this.resetFields()
    }
  }
}
</script>
